/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.baidu.aip.unit.parser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.aip.unit.exception.UnitError;
import com.baidu.aip.unit.model.ResponseResult;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class DefaultParser implements Parser<ResponseResult> {
	
	private static final Logger Log = LoggerFactory.getLogger(DefaultParser.class);

    @Override
    public ResponseResult parse(String json) throws UnitError {
        Log.error("DefaultParser:" + json);
        try {
        	Gson gson = new GsonBuilder()
            	    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            	    .create();
        	ResponseResult response = gson.fromJson(json, ResponseResult.class);
            
            if (response.getErrorCode() != 0) {
            	UnitError error = new UnitError(response.getErrorCode(), response.getErrorMsg());
                throw error;
            }
            
            response.setJsonRes(json);
            return response;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            UnitError error = new UnitError(UnitError.ErrorCode.JSON_PARSE_ERROR, "Json parse error:" + json, e);
            throw error;
        }
    }
}
